package lyq.spec.edu.week12_home02;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ActivityFirst extends AppCompatActivity implements MyListViewUtils.LoadListener{
    private MyListViewUtils listViewUtils;
    private List<Wechat> wechatList = new ArrayList<Wechat>();
    private static final String TAG = "ActivityFirst";
    private ArrayAdapter<String> adapter;
    int a = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first);

        sendRequestWithOkHttp();
        // 初始化数据

        //addList();

        // 获取控件

        Init();

        // 适配器加载数据

        adapter = new WeChatAdapter(ActivityFirst.this, R.layout.wechat_first, wechatList);

        listViewUtils.setAdapter(adapter);

        listViewUtils.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Wechat wechat = wechatList.get(position);
                //Toast.makeText(ActivityFirst.this,wechat.getText(),Toast.LENGTH_SHORT).show();

                //position 点击的Item位置，从0开始算
                Intent intent=new Intent(ActivityFirst.this,ActivityObtained.class);
                intent.putExtra("WeChat_Text",wechat.getText());//传递给下一个Activity的值
                startActivity(intent);//启动Activity
            }
        });
        /*sendRequestWithOkHttp();
        // 构造Adapter
        WeChatAdapter adapter = new WeChatAdapter(ActivityFirst.this, R.layout.wechat_first, wechatList);
        // 找到ListView
        ListView listView = (ListView) findViewById(R.id.list_view);
        // 将Adapter应用到ListView
        listView.setAdapter(adapter);*/


        /*//点击listView跳转并传输数据
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Wechat wechat = wechatList.get(position);
                //Toast.makeText(ActivityFirst.this,wechat.getText(),Toast.LENGTH_SHORT).show();

                //position 点击的Item位置，从0开始算
                Intent intent=new Intent(ActivityFirst.this,ActivityObtained.class);
                intent.putExtra("WeChat_Text",wechat.getText());//传递给下一个Activity的值
                startActivity(intent);//启动Activity
        }
        });*/

    }


    private void sendRequestWithOkHttp(){
        new Thread(new Runnable() {   //开启一个子线程
            @Override
            public void run() {
                try {
                    //构造客户端,相当于浏览器
                    OkHttpClient client = new OkHttpClient();
                    //构造请求，相当于在浏览器里输入地址
                    Request request = new Request
                            .Builder()
                            /*.url("http://www.yyjsx.xyz/api/message/listByCategory?messageCategory=WECHAT")*/
                            .url("http://www.yyjsx.xyz/api/message/find?messageCategory=WECHAT&start="+a)
                            .build();
                    //发送请求，相当于在浏览器里按回车
                    Response response = client.newCall(request).execute(); //异常捕获
                    // 更新ListView
                    String body = response.body().string();
                    //Log.d(TAG,body);
                    parseJson(body);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void parseJson(String jsonStr){
        try {
            JSONObject jobj = new JSONObject(jsonStr);
            String dataStr  = jobj.getString("data");

            Gson gson = new Gson();
            List<Message> messageList = gson.fromJson(dataStr,new TypeToken<List<Message>>(){}.getType());
            for(Message m : messageList){
                //Log.d(TAG,m.getPreview());
                wechatList.add(new Wechat(m.getTitle(),m.getSummary(),m.getPreview()));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void Init() {

        listViewUtils = (MyListViewUtils) findViewById(R.id.list_view);

        listViewUtils.setInteface(this);

    }
    @Override
    public void onLoad() {
        // 设置延时三秒获取时局，用于显示加载效果

        new Handler().postDelayed(new Runnable() {



            @Override

            public void run() {

                // 这里处理请求返回的结果（这里使用模拟数据）



                // 更新数据

                adapter.notifyDataSetChanged();

                // 加载完毕

                listViewUtils.loadComplete();

            }

        }, 3000);



    }

    @Override
    public void PullLoad() {
        // 设置延时三秒获取时局，用于显示加载效果

        new Handler().postDelayed(new Runnable() {



            @Override

            public void run() {

                // 这里处理请求返回的结果（这里使用模拟数据）
                a +=10;
                sendRequestWithOkHttp();
                //wechatList.add("这是上拉刷新添加的数据");

                // 更新数据

                adapter.notifyDataSetChanged();

                // 加载完毕

                listViewUtils.loadComplete();

            }

        }, 3000);
    }
}